#include "WarnRuleSet.h"
#include "ui_WarnRuleSet.h"
#include "SnaillTcpClient.h"
#include <QDebug>
WarnRuleSet::WarnRuleSet(QWidget *parent,deviceModel*deviceModel,userModel*userModel) :
    QWidget(parent),
    ui(new Ui::WarnRuleSet),
    dModel(deviceModel),
    uModel(userModel)
{
    ui->setupUi(this);
    qDebug()<<"+++"<<dModel->id;
    QString device_id=dModel->id;
    connect(ui->pushButton,&QPushButton::clicked,this,[=](){
        QJsonObject jsonObj;
        qDebug()<<"==="<<device_id;
        jsonObj["action"] ="warnrole";
        jsonObj["device_id"] =device_id;
        jsonObj["description"] ="设置最低最高温湿度";
        jsonObj["maxHemperature"] =ui->lineEdit_3->text();
        jsonObj["minHemperature"] =ui->lineEdit_4->text();
        jsonObj["maxTemperature"] =ui->lineEdit->text();
        jsonObj["minTemperature"] =ui->lineEdit_2->text();
        jsonObj["actiond"] ="邮件";
        LOG_INFO(device_id+"设置规则");
        if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
            //  qDebug() << "deviceList data sent successfully";
        } else {

            return ;
        }
    });
    connect(SnaillTcpClient::instance(), &SnaillTcpClient::dataReceived, this, &WarnRuleSet::handleDataReceived);

//    QJsonObject jsonObj;
//    jsonObj["action"] ="getwarnrole";
//    jsonObj["device_id"] =device_id;
//    if (SnaillTcpClient::instance()->sendJsonData(jsonObj)) {
//        //  qDebug() << "deviceList data sent successfully";
//    } else {

//        return ;
//    }
}

WarnRuleSet::~WarnRuleSet()
{
    delete ui;
}

void WarnRuleSet::handleDataReceived(const QByteArray &data)
{

    QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonDoc.object();
    QString action = jsonObj["action"].toString();
    qDebug()<<"action==+++=="<<action;
    if(action=="warnrole"){
        qDebug()<<"action=="<<action;
        QString coded = jsonObj["code"].toString();
        int code = coded.toInt();
        if(code==QUERY_FAILED){
            ui->label->setText("添加失败");

        }else{
            ui->label->setText("添加成功");
        }
    }else if (action=="getwarnrole") {

        QString rid=jsonObj["id"].toString();
        qDebug()<<"进入了有数"<<jsonObj;
        if(rid!="-1"){
            qDebug()<<"进入了有数据1"<<jsonObj;
            qDebug()<<"进入了有数据2"<<data;
            ui->lineEdit->setText( jsonObj["maxTemperature"].toString());
            ui->lineEdit_2->setText(jsonObj["minTemperature"].toString());
            ui->lineEdit_3->setText(jsonObj["maxHemperature"].toString());
            ui->lineEdit_4->setText(jsonObj["minHemperature"].toString());
qDebug()<<"进入了有数据3"<<jsonObj;
        }else {
            qDebug()<<"进入了无数据";
        }


    }
}

